from flask import Flask, request, render_template
import MySQLdb
app = Flask(__name__)
# 配置数据库连接
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = '3306'  # 请替换为你的数据库密码
app.config['MYSQL_DATABASE_DB'] = 'school'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
# 初始化 MySQLdb 连接
def get_db_connection():
    return MySQLdb.connect(
        user=app.config['MYSQL_DATABASE_USER'],
        passwd=app.config['MYSQL_DATABASE_PASSWORD'],
        db=app.config['MYSQL_DATABASE_DB'],
        host=app.config['MYSQL_DATABASE_HOST']
    )
@app.route('/')
def index():
    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute('SELECT * FROM question2')  # 修改为从question2表中获取判断题
    questions = cursor.fetchall()
    cursor.close()
    conn.close()
    return render_template('exam.html', questions=questions)  # 修改模板名称
@app.route('/submit', methods=['POST'])
def submit():
    answers = request.form  # 获取提交的表单数据
    score = 0
    total = 0
    conn = get_db_connection()
    cursor = conn.cursor()

    for question_id, user_answer in answers.items():
        question_id = question_id.split('_')[1]  # 从 name 属性中提取实际问题ID
        cursor.execute('SELECT correct_answer FROM question2 WHERE id = %s', (question_id,))
        correct_answer = cursor.fetchone()

        if correct_answer:  # 确保取到了正确答案
            total += 1
            correct_answer_value = correct_answer[0]  # 获取正确答案的值
            print(f"User Answer: {user_answer}, Correct Answer: {correct_answer_value}")  # 调试信息

            if user_answer == correct_answer_value:
                score += 1
    return f'你的分数: {score}/{total}'
    cursor.close()
    conn.close()
if __name__ == '__main__':
    app.run(debug=True)